/*注册组件*/
import {Button, Checkbox, Chip, CircularProgress, Input, Spacer, Tab, Tabs, Card, CardBody} from "@nextui-org/react";
import React, {useState} from "react";
import {validateParameterRes} from "@/app/utils/validation";
import ToastUtil from "@/app/utils/toastUtil";
import {NotificationIcon} from "@/app/assets/icons/NotificationIcon";
import {useRouter} from "next/navigation";
import PubSub from 'pubsub-js'
import {delay} from "framer-motion";
import RegisterService, {MobileRegisterService} from "@/app/service/registerService";
import {SendVerificationCode} from "@/app/service/loginService";
import { IoMdArrowBack } from "react-icons/io";
import { IoCheckmarkCircle } from "react-icons/io5";

/**
 * 账号密码注册表单
 * @param loading
 * @param setLoading
 * @param setSuccess
 * @param setError
 * @param setResData
 * @param isChecked
 * @param setChecked
 * @constructor
 */
function PasswordRegisterForm({loading, setLoading, setSuccess, setError, setResData, isChecked, setChecked}: any) {
    /* 分步状态 (1:基本信息, 2:设置密码, 3:完成注册) */
    const [step, setStep] = useState(1);
    
    /*定义注册数据和状态*/
    const [username, setUsername] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [nickname, setNickname] = useState('');
    
    /* 验证状态 */
    const [usernameValid, setUsernameValid] = useState(false);
    const [emailValid, setEmailValid] = useState(false);
    
    /* 检查用户名和邮箱 - 简单的前端验证 */
    const validateBasicInfo = () => {
        // 实际应用中应该有更复杂的验证和后端检查用户名是否存在
        if (!username || username.length < 3) {
            ToastUtil("用户名至少需要3个字符", '🤨', "warning");
            return false;
        }
        
        // 简单的邮箱格式验证
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!email || !emailRegex.test(email)) {
            ToastUtil("请输入有效的邮箱地址", '🤨', "warning");
            return false;
        }
        
        setUsernameValid(true);
        setEmailValid(true);
        return true;
    };
    
    /* 验证密码 */
    const validatePassword = () => {
        if (!password || password.length < 6) {
            ToastUtil("密码至少需要6个字符", '🤨', "warning");
            return false;
        }
        
        if (password !== confirmPassword) {
            ToastUtil("两次输入的密码不一致", '🤨', "warning");
            return false;
        }
        
        return true;
    };
    
    /* 进入下一步 */
    const nextStep = () => {
        if (step === 1) {
            if (validateBasicInfo()) {
                setStep(2);
            }
        } else if (step === 2) {
            if (validatePassword()) {
                setStep(3);
            }
        }
    };
    
    /* 返回上一步 */
    const goBack = () => {
        if (step > 1) {
            setStep(step - 1);
        }
    };
    
    /* 提交注册 */
    const submitRegistration = () => {
        /*调用注册服务*/
        RegisterService({
            setLoading,
            setSuccess,
            setError,
            setResData,
            isChecked,
            username,
            password,
            confirmPassword,
            email,
            nickname
        }).then(r => {});
    };

    return (
        <div className="w-full">
            {/* 步骤指示器 */}
            <div className="flex justify-between mb-4 relative">
                <div className="absolute top-1/2 h-1 bg-gray-200 w-full -z-10"></div>
                <div className={`z-10 w-8 h-8 rounded-full flex items-center justify-center 
                               ${step >= 1 ? 'bg-primary text-white' : 'bg-gray-200'}`}>
                    {step > 1 ? <IoCheckmarkCircle size={20} /> : 1}
                </div>
                <div className={`z-10 w-8 h-8 rounded-full flex items-center justify-center 
                               ${step >= 2 ? 'bg-primary text-white' : 'bg-gray-200'}`}>
                    {step > 2 ? <IoCheckmarkCircle size={20} /> : 2}
                </div>
                <div className={`z-10 w-8 h-8 rounded-full flex items-center justify-center 
                               ${step >= 3 ? 'bg-primary text-white' : 'bg-gray-200'}`}>
                    3
                </div>
            </div>

            {/* 步骤1: 基本信息 */}
            {step === 1 && (
                <Card className="mb-4">
                    <CardBody>
                        <h3 className="text-md font-medium mb-3">步骤1: 基本信息</h3>
                        <Input 
                            isClearable
                            className="dark:text-white"
                            type="text"
                            label="用户名"
                            variant="faded"
                            placeholder="请输入您的用户名"
                            value={username}
                            onChange={({target: {value}}) => setUsername(value)}
                            isRequired={true}
                        />
                        <Spacer y={2} />
                        <Input 
                            isClearable
                            className="dark:text-white"
                            type="email"
                            label="邮箱"
                            variant="faded"
                            placeholder="请输入您的邮箱"
                            value={email}
                            onChange={({target: {value}}) => setEmail(value)}
                            isRequired={true}
                        />
                        <Spacer y={2} />
                        <Button 
                            fullWidth 
                            color="primary" 
                            onClick={nextStep}
                            isDisabled={!username || !email}
                        >
                            下一步
                        </Button>
                    </CardBody>
                </Card>
            )}

            {/* 步骤2: 设置密码 */}
            {step === 2 && (
                <Card className="mb-4">
                    <CardBody>
                        <div className="flex items-center mb-3">
                            <Button 
                                isIconOnly 
                                variant="light" 
                                onClick={goBack}
                                className="mr-2"
                            >
                                <IoMdArrowBack />
                            </Button>
                            <h3 className="text-md font-medium">步骤2: 设置密码</h3>
                        </div>
                        
                        <Input
                            type="password"
                            className="dark:text-white mb-3"
                            label="密码"
                            variant="faded"
                            placeholder="请输入您的密码"
                            value={password}
                            onChange={({target: {value}}) => setPassword(value)}
                            isRequired={true}
                        />
                        
                        <Input
                            type="password"
                            className="dark:text-white mb-3"
                            label="确认密码"
                            variant="faded"
                            placeholder="请再次输入您的密码"
                            value={confirmPassword}
                            onChange={({target: {value}}) => setConfirmPassword(value)}
                            isRequired={true}
                        />
                        
                        <Spacer y={2} />
                        
                        <Button 
                            fullWidth 
                            color="primary" 
                            onClick={nextStep}
                            isDisabled={!password || !confirmPassword}
                        >
                            下一步
                        </Button>
                    </CardBody>
                </Card>
            )}

            {/* 步骤3: 完成注册 */}
            {step === 3 && (
                <Card className="mb-4">
                    <CardBody>
                        <div className="flex items-center mb-3">
                            <Button 
                                isIconOnly 
                                variant="light" 
                                onClick={goBack}
                                className="mr-2"
                            >
                                <IoMdArrowBack />
                            </Button>
                            <h3 className="text-md font-medium">步骤3: 完成注册</h3>
                        </div>
                        
                        <Input 
                            isClearable
                            className="dark:text-white mb-3"
                            type="text"
                            label="昵称（选填）"
                            variant="faded"
                            placeholder="请输入您的昵称"
                            value={nickname}
                            onChange={({target: {value}}) => setNickname(value)}
                        />
                        
                        <Checkbox 
                            classNames={{label: "text-small"}} 
                            isSelected={isChecked} 
                            onValueChange={setChecked}
                        >
                            同意服务协议和隐私协议
                        </Checkbox>
                        
                        <Spacer y={2} />
                        
                        <Button 
                            fullWidth 
                            color="primary" 
                            onClick={submitRegistration}
                            isDisabled={!isChecked}
                        >
                            完成注册
                        </Button>
                    </CardBody>
                </Card>
            )}
        </div>
    );
}

/**
 * 手机号注册分步表单
 * @param loading
 * @param setLoading
 * @param setSuccess
 * @param setError
 * @param setResData
 * @param isChecked
 * @param setChecked
 * @constructor
 */
function MobileRegisterForm({loading, setLoading, setSuccess, setError, setResData, isChecked, setChecked}: any) {
    /* 分步状态 (1:手机号, 2:验证码, 3:设置密码) */
    const [step, setStep] = useState(1);
    
    /* 注册数据 */
    const [mobile, setMobile] = useState('');
    const [code, setCode] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [nickname, setNickname] = useState('');
    
    /* 验证状态 */
    const [mobileVerified, setMobileVerified] = useState(false);
    const [codeVerified, setCodeVerified] = useState(false);
    
    /* 倒计时 */
    const [countdown, setCountdown] = useState(0);
    
    /* 发送验证码 */
    const sendCode = () => {
        if (countdown > 0) return;
        
        if (!mobile || mobile.length !== 11) {
            ToastUtil("请输入正确的手机号", '🤨', "warning");
            return;
        }
        
        SendVerificationCode({mobile, type: 'REGISTER'}).then(success => {
            if (success) {
                setMobileVerified(true);
                setStep(2); // 进入验证码步骤
                setCountdown(60);
                const timer = setInterval(() => {
                    setCountdown(prevCountdown => {
                        if (prevCountdown <= 1) {
                            clearInterval(timer);
                            return 0;
                        }
                        return prevCountdown - 1;
                    });
                }, 1000);
            }
        });
    };
    
    /* 验证验证码 - 这里简化处理，实际应有后端验证 */
    const verifyCode = () => {
        if (!code || code.length < 4) {
            ToastUtil("请输入正确的验证码", '🤨', "warning");
            return;
        }
        
        // 简单验证，实际应用中应通过API验证
        setCodeVerified(true);
        setStep(3); // 进入设置密码步骤
    };
    
    /* 提交注册 */
    const submitRegistration = () => {
        /*调用注册服务*/
        MobileRegisterService({
            setLoading,
            setSuccess,
            setError,
            setResData,
            isChecked,
            mobile,
            code,
            password,
            confirmPassword,
            nickname
        }).then(r => {});
    };
    
    /* 返回上一步 */
    const goBack = () => {
        if (step > 1) {
            setStep(step - 1);
        }
    };
    
    return (
        <div className="w-full">
            {/* 步骤指示器 */}
            <div className="flex justify-between mb-4 relative">
                <div className="absolute top-1/2 h-1 bg-gray-200 w-full -z-10"></div>
                <div className={`z-10 w-8 h-8 rounded-full flex items-center justify-center 
                               ${step >= 1 ? 'bg-primary text-white' : 'bg-gray-200'}`}>
                    {step > 1 ? <IoCheckmarkCircle size={20} /> : 1}
                </div>
                <div className={`z-10 w-8 h-8 rounded-full flex items-center justify-center 
                               ${step >= 2 ? 'bg-primary text-white' : 'bg-gray-200'}`}>
                    {step > 2 ? <IoCheckmarkCircle size={20} /> : 2}
                </div>
                <div className={`z-10 w-8 h-8 rounded-full flex items-center justify-center 
                               ${step >= 3 ? 'bg-primary text-white' : 'bg-gray-200'}`}>
                    3
                </div>
            </div>

            {/* 步骤1: 输入手机号 */}
            {step === 1 && (
                <Card className="mb-4">
                    <CardBody>
                        <h3 className="text-md font-medium mb-3">步骤1: 输入手机号</h3>
                        <Input 
                            isClearable
                            className="dark:text-white"
                            type="tel"
                            label="手机号"
                            variant="faded"
                            placeholder="请输入您的手机号"
                            value={mobile}
                            onChange={({target: {value}}) => setMobile(value)}
                            isRequired={true}
                        />
                        <Spacer y={2} />
                        <Button 
                            fullWidth 
                            color="primary" 
                            onClick={sendCode}
                            isDisabled={!mobile || mobile.length !== 11}
                        >
                            获取验证码
                        </Button>
                    </CardBody>
                </Card>
            )}

            {/* 步骤2: 验证手机 */}
            {step === 2 && (
                <Card className="mb-4">
                    <CardBody>
                        <div className="flex items-center mb-3">
                            <Button 
                                isIconOnly 
                                variant="light" 
                                onClick={goBack}
                                className="mr-2"
                            >
                                <IoMdArrowBack />
                            </Button>
                            <h3 className="text-md font-medium">步骤2: 验证手机</h3>
                        </div>
                        
                        <p className="text-sm text-gray-500 mb-3">验证码已发送至: {mobile}</p>
                        
                        <Input 
                            className="dark:text-white"
                            type="text"
                            label="验证码"
                            variant="faded"
                            placeholder="请输入验证码"
                            value={code}
                            onChange={({target: {value}}) => setCode(value)}
                            isRequired={true}
                        />
                        
                        <Spacer y={1} />
                        
                        <Button 
                            size="sm" 
                            variant="flat" 
                            color="primary" 
                            isDisabled={countdown > 0}
                            onClick={sendCode}
                        >
                            {countdown > 0 ? `重新发送(${countdown})` : "重新发送"}
                        </Button>
                        
                        <Spacer y={2} />
                        
                        <Button 
                            fullWidth 
                            color="primary" 
                            onClick={verifyCode}
                            isDisabled={!code}
                        >
                            下一步
                        </Button>
                    </CardBody>
                </Card>
            )}

            {/* 步骤3: 设置密码 */}
            {step === 3 && (
                <Card className="mb-4">
                    <CardBody>
                        <div className="flex items-center mb-3">
                            <Button 
                                isIconOnly 
                                variant="light" 
                                onClick={goBack}
                                className="mr-2"
                            >
                                <IoMdArrowBack />
                            </Button>
                            <h3 className="text-md font-medium">步骤3: 完成注册</h3>
                        </div>
                        
                        <Input
                            type="password"
                            className="dark:text-white mb-3"
                            label="密码"
                            variant="faded"
                            placeholder="请输入您的密码"
                            value={password}
                            onChange={({target: {value}}) => setPassword(value)}
                            isRequired={true}
                        />
                        
                        <Input
                            type="password"
                            className="dark:text-white mb-3"
                            label="确认密码"
                            variant="faded"
                            placeholder="请再次输入您的密码"
                            value={confirmPassword}
                            onChange={({target: {value}}) => setConfirmPassword(value)}
                            isRequired={true}
                        />
                        
                        <Input 
                            isClearable
                            className="dark:text-white mb-3"
                            type="text"
                            label="昵称（选填）"
                            variant="faded"
                            placeholder="请输入您的昵称"
                            value={nickname}
                            onChange={({target: {value}}) => setNickname(value)}
                        />
                        
                        <Checkbox 
                            classNames={{label: "text-small"}} 
                            isSelected={isChecked} 
                            onValueChange={setChecked}
                        >
                            同意服务协议和隐私协议
                        </Checkbox>
                        
                        <Spacer y={2} />
                        
                        <Button 
                            fullWidth 
                            color="primary" 
                            onClick={submitRegistration}
                            isDisabled={!password || !confirmPassword || !isChecked}
                        >
                            完成注册
                        </Button>
                    </CardBody>
                </Card>
            )}
        </div>
    );
}

/**
 * 注册页
 * @constructor
 */
export default function Register() {
    const router = useRouter();
    /*Loading状态*/
    const [loading, setLoading] = useState(false);

    /*结果状态定义*/
    const [success, setSuccess] = useState(false);
    const [error, setError] = useState(false);
    const [resData, setResData] = useState('');

    /*服务协议Checkbox*/
    const [isChecked, setChecked] = useState(false);
    
    /*Tab选择*/
    const [selected, setSelected] = useState("mobile");

    return (
        <>
            <Tabs
                aria-label="注册选项"
                selectedKey={selected}
                onSelectionChange={setSelected as any}
                variant="underlined"
                color="primary"
                classNames={{
                    tabList: "gap-6 w-full relative rounded-none p-0 border-b border-divider",
                    cursor: "w-full bg-primary",
                    tab: "max-w-fit px-2 h-12",
                }}
            >
                <Tab key="mobile" title="手机号注册">
                    <MobileRegisterForm 
                        loading={loading} 
                        setLoading={setLoading}
                        setSuccess={setSuccess}
                        setError={setError}
                        setResData={setResData}
                        isChecked={isChecked}
                        setChecked={setChecked}
                    />
                </Tab>
                <Tab key="password" title="账号密码注册">
                    <PasswordRegisterForm 
                        loading={loading} 
                        setLoading={setLoading}
                        setSuccess={setSuccess}
                        setError={setError}
                        setResData={setResData}
                        isChecked={isChecked}
                        setChecked={setChecked}
                    />
                </Tab>
            </Tabs>
            
            {/*Loading*/}
            <div className={'flex justify-center'}>
                <CircularProgress className={!loading ? 'hidden' : ''} color={"default"} size={"lg"}
                                  aria-label={'加载中...'}/>
            </div>
            <Spacer y={0.5}/>
            <div className={'flex justify-center'}>
                {/*灵动岛😎*/}
                <Chip
                    className={!success && !error ? 'hidden' : ''}
                    endContent={<NotificationIcon size={18}/>}
                    variant="flat"
                    color={success ? error ? 'danger' : 'success' : 'danger'}
                >
                    {resData}
                </Chip>
            </div>
        </>
    )
}